package com.framework.main.sys.dept.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import com.framework.base.dao.IDManager;
import com.framework.base.service.BaseServiceImp;
import com.framework.main.sys.dept.dao.DeptDao;
import com.framework.main.sys.dept.domain.DeptVO;
import com.framework.main.sys.dept.domain.SysUserDeptVO;
import com.framework.main.sys.user.domain.UserVo;

/**
 * Title:部门（ServiceImp） 
 * Description:处理与部门相关的业务
 * tabaleName(对应的表名): SYS_DEPT
 * Copyright: Copyright (c) 年份
 * Company: www.51wuxia.com
 * @author：www.51wuxia.com
 * @version 1.0
 */
public class DeptServiceImp extends BaseServiceImp implements DeptService{
	private DeptDao deptDao;
	
	public DeptDao getDeptDao() {
		return deptDao;
	}
	
	public void setDeptDao(DeptDao deptDao) {
		this.deptDao = deptDao;
	}
	
	/**
	 * 显示左侧树形
	 */
//	@SuppressWarnings("unchecked")
//	public List<DeptVO> toListsj() throws Exception {
//		List<DeptVO> deptList=this.getDeptDao().query("toListsj");
//		return deptList;
//	}
	@SuppressWarnings("unchecked")
	public List<DeptVO> toListsj() throws Exception {
		
		HashMap<String,DeptVO> middleMap=new LinkedHashMap<String, DeptVO>();
		List<DeptVO> deptList=this.getDeptDao().query("toListsj");
		for (DeptVO deptVO : deptList) {
			middleMap.put(deptVO.getIdf(), deptVO);
		}
		
		List<UserVo> userList=this.getDeptDao().toUsersWithDept();
		for (UserVo userVo : userList) {
			if(userVo!=null){
				DeptVO deptVo=middleMap.get(userVo.getDeptidf());
				if(deptVo!=null){
					if(deptVo.getUserList()==null){
						deptVo.setUserList(new ArrayList<UserVo>());
					}
					deptVo.getUserList().add(userVo);
					middleMap.put(deptVo.getIdf(),deptVo);
				}
				
			}
			
		}
		deptList=new ArrayList<DeptVO>();
		for (Object object : middleMap.values()) {
			deptList.add((DeptVO) object);
		}
		return deptList;
	}
	
	/**
	 * 查询人员选择页面显示数据 （用户表数据）
	 */

	@SuppressWarnings("unchecked")
	public List toselectUser(String url, String pk) throws Exception {
		return getDeptDao().query(url, pk);
	}
	
	/**
	 * 分配人员（部门用户中间表数据）
	 */
	public void doInsertUR(String pk,String userid)throws Exception{		
		//删除人员-角色中间表
		this.getBaseDao().doUpdate("doDeleteUD", pk);
		String[] ss=userid.split(",");
		for (String uidf : ss) {
			SysUserDeptVO vo=new SysUserDeptVO();
			vo.setIdf(IDManager.generateID());
			vo.setUseridf(uidf);
			vo.setDeptIdf(pk);
			this.getBaseDao().doInsert("doInsertUD", vo);
		}
	}
	
	public String doDelete(String pks) throws Exception {
		return null;
	}
	
	/**
	 * 登录返回用户所在的部门
	 * @param userId
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public List toLoginQueryDept(String userId)throws Exception{
		return this.getBaseDao().queryForList("toListLogin", userId);
	}
}  
